/*
          next maxtri

        P
        ↓
        
N →         0	4	1	5	3	7	8
        0	0	0	4	4	1	1	8
        1	0	0	4	4	1	1	8
        3	0	0	4	4	1	1	8
        4	5	5	3	3	7	7	3
        5	5	5	3	3	7	7	3
        7	5	5	3	3	7	7	3
        8	-	-	-	-	-	-	8

        x   a       x   c       y   b       x   b       y   a       y   c       x   b
         \ /         \ /         \ /         \ /         \ /         \ /         \ /
          0           1           3           4           5           7           8
         / \         / \         / \         / \         / \         / \         / \
        a   x       b   x       c   x       a   y       b   y       c   y       b   x

        x   b       x   b
          4    <==>   8
        a   y       b   x
*/

export const NEXT_MAP = {
    0: { 0: 0,  4: 0,  1: 4,  5: 4,  3: 1,  7: 1,  8: 8 },
    1: { 0: 0,  4: 0,  1: 4,  5: 4,  3: 1,  7: 1,  8: 8 },
    3: { 0: 0,  4: 0,  1: 4,  5: 4,  3: 1,  7: 1,  8: 8 },
    4: { 0: 5,  4: 5,  1: 3,  5: 3,  3: 7,  7: 7,  8: 3 },
    5: { 0: 5,  4: 5,  1: 3,  5: 3,  3: 7,  7: 7,  8: 3 },
    7: { 0: 5,  4: 5,  1: 3,  5: 3,  3: 7,  7: 7,  8: 3 },
    8: { 0: -1, 4: -1, 1: -1, 5: -1, 3: -1, 7: -1, 8: 8 },
};

/**
 * 
 * @param {Number} p prev
 * @param {Number} n next
 * @returns next num after convertion
 */
export const nx = (p, n) => NEXT_MAP[p]?.[n] ?? -1;


export const next = (num) => {
    let num1 = [0, ...num, 8];
    let num2 = [];
    for (let i = 0; i < num1.length - 1; i++) {
        num2.push(nx(num1[i], num1[i + 1]))
    }

    // const num2 = num1.silce(0,-1).map((n, idx) => nx(n, n[idx + 1]));

    while (num2[0] === 0) {
        num2.shift();
    }
    while (num2[num2.length - 1] === 8) {
        num2.pop();
    }
    return num2;
}

export const next2 = (num) => {
    let num2 = next(num);
    while (num2[num2.length - 1] === 0) {
        num2.pop();
    }
    return num2;
}

const path = (num) => {
    let num1 = Array.from(num);
    while (true) {
        if (num1.length <= 1) break;
        console.log(num1.join(''));
        num1 = next(num1);
    }
}

const pathStr = (str) => path(str.split('').map(e => +e));

// test unit
const tuint = () => {
    console.log(next([3, 5]));//"35->143"
    console.log(next([1, 4, 3]));//"143->407"
    console.log(next([4, 0, 4, 0, 3]));//"40403->5051"

    path([3, 5]);
};

// tuint();